package com.chen.base.module.redis.utils;

import com.chen.base.module.redis.service.CacheService;
import com.chen.base.utils.SpringContextHolder;
import com.chen.base.utils.basic.ContainerUtil;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

/**
 * 基于redis缓存存储的CRUD
 * @author: Long
 * @date: 2023/7/21 23:18
 **/
@UtilityClass
public class CacheUtil {

    /**
     * 根据判断条件获取单个实体
     * @param key 缓存key
     * @param tClass 元素类型
     * @param filter 判断条件
     * @return one entity
     */
    public <T> T getBy(String key, Class<T> tClass, Predicate<T> filter){
        CacheService cacheService = SpringContextHolder.getBean(CacheService.class);
        List<T> list = cacheService.lGetAll(key, tClass);
        for (T t : list) {
            if (filter.test(t)){
                return t;
            }
        }
        return null;
    }

    /**
     * 保存或更新元素
     * @param key ket
     * @param t 元素
     * @param tClass 元素类型
     * @param filter 更新条件
     */
    public <T> void saveOrUpdate(String key, T t, Class<T> tClass, Predicate<T> filter){
        CacheService cacheService = SpringContextHolder.getBean(CacheService.class);
        List<T> list = cacheService.lGetAll(key, tClass);

        Map<Integer, T> anIf = ContainerUtil.replaceIf(list, t, filter);
        if (anIf != null){
            Integer index = new ArrayList<>(anIf.keySet()).get(0);
            cacheService.lUpdateIndex(key, index, t, false);
            return;
        }
        cacheService.lSet(key, t);
    }

    /**
     * 删除元素
     * @param key 缓存key
     * @param tClass 元素类型
     * @param filter 删除条件
     */
    public <T> void delete(String key, Class<T> tClass, Predicate<T> filter){
        CacheService cacheService = SpringContextHolder.getBean(CacheService.class);
        List<T> list = cacheService.lGetAll(key, tClass);
        if (list.removeIf(filter)){
            cacheService.del(key);
            for (T t : list) {
                cacheService.lSet(key,t);
            }
        }
    }
}
